package com.liuyfly.leetcode.questions;

import com.liuyfly.leetcode.model.ListNode;
import com.liuyfly.leetcode.util.LeetcodeUtil;

/**
 * @author liuyangfang at 2022-09-02 13:51
 */
public class Question0019 {

    /**
     * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
     * 
     * <pre>
        示例 1：
        输入：head = [1,2,3,4,5], n = 2
        输出：[1,2,3,5]
     * </pre>
     * 
     * <pre>
        示例 2：
        输入：head = [1], n = 1
        输出：[]
     * </pre>
     * 
     * <pre>
        示例 3：
        输入：head = [1,2], n = 1 
        输出：[1]
     * </pre>
     * 
     * <br/>
     * <br/>
     * 链接：https://leetcode.cn/problems/remove-nth-node-from-end-of-list
     */
    public static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode nullNode = new ListNode();
        nullNode.next = head;
        ListNode first = nullNode;
        ListNode second = nullNode;
        for (int i = 0; i < n; i++) {
            second = second.next;
        }
        if (second.next == null) {
            return head.next;
        }
        while (second.next != null) {
            first = first.next;
            second = second.next;
        }
        if (first.next != null) {
            if (first.next.next != null) {
                first.next = first.next.next;
            } else {
                first.next = null;
            }
        }
        return head;
    }

    public static void main(String[] args) {
        ListNode head = LeetcodeUtil.initListNode(null, 10);
        LeetcodeUtil.printListNode(head);
        ListNode result = removeNthFromEnd(head, 1);
        LeetcodeUtil.printListNode(result);
    }
}
